package com.quanyue.music.file.service.impl;

import com.quanyue.music.domain.entity.UserSurvey;
import com.quanyue.music.file.mapper.SurveyMapper;
import com.quanyue.music.file.service.SurveyService;
import com.quanyue.music.file.type.SurveyDetail;
import com.shzisg.mybatis.mapper.page.Page;
import com.shzisg.mybatis.mapper.page.PageRequest;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class SurveyServiceImpl implements SurveyService {
    private final String path = "/opt/music/admin/server/static/dist/excel";
    @Autowired
    private SurveyMapper surveyMapper;

    @Override
    public void addSurvey(UserSurvey userSurvey, String userId) {
        userSurvey.setUserId(userId);
        userSurvey.setCreateTime(LocalDateTime.now());
        surveyMapper.insert(userSurvey);
    }

    @Override
    public void deleteSurvey(String id) {
        surveyMapper.deleteOne(id);
    }

    @Override
    public Page<SurveyDetail> findSurveyDetail(PageRequest request) {
        request.setOrderBy("s.create_time");
        request.setAsc(false);
        return surveyMapper.findSurveyDetail(request);
    }

    @Override
    public String surveyExcel() {
        List<SurveyDetail> details = surveyMapper.findAllDetail();
        try {
            String fileName = "survey.xls";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            //  打开文件
            WritableWorkbook book = Workbook.createWorkbook(new File(path + "/", fileName));
            //  生成名为“第一页”的工作表，参数0表示这是第一页
            WritableSheet sheet = book.createSheet(" 第一页 ", 0);

            //  将定义好的单元格添加到工作表中  在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
            sheet.addCell(new Label(0, 0, "用户昵称"));
            sheet.addCell(new Label(1, 0, "用户头像"));
            sheet.addCell(new Label(2, 0, "推荐指数"));
            sheet.addCell(new Label(3, 0, "反馈意见"));
            sheet.addCell(new Label(4, 0, "评价时间"));

            int row = 1;
            for (SurveyDetail detail : details) {
                int column = 0;
                sheet.addCell(new Label(column++, row, detail.getNickName()));
                sheet.addCell(new Label(column++, row, detail.getHeadImage()));
                sheet.addCell(new Label(column++, row, detail.getNominateIndex()));
                sheet.addCell(new Label(column++, row, detail.getSuggest()));
                sheet.addCell(new Label(column++, row, detail.getCreateTime().toString()));
                ++row;
            }
            //  写入数据并关闭文件
            book.write();
            book.close();
            return fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
